import { Component } from "react";
import { Layer, Map, Point } from "../../modules/CloudMap/src/Cloud";
import Cesium from '../../modules/cesium/Cesium';
import JIANKONG from '../../assets/icon/jiankong.png'
const scss = require('../../assets/styles/map.module.scss');
const windows: any = window;
const { mapData } = require("../data");
const CLOUD_API = windows['env'];
interface MapProps {

}
interface MapState {
    onlineCloudImgList: any[];
    imgRightIs_: boolean;
    MapObject: any[];
    Map2D3DIs_: boolean;
    PointDataList: any[];
}
let layers: any = null;
export default class MapSkin extends Component<MapProps, MapState> {
    maps: any;
    layer: any;
    viewer: any;
    eventHandler: any;
    constructor(props: any) {
        super(props)
        this.state = {
            onlineCloudImgList: [],
            imgRightIs_: false,
            MapObject: [],
            Map2D3DIs_: true,
            PointDataList: []
        };
    }

    componentDidMount() {
        this.initImg()
    }
    // 初始化地图参数
    initImg = () => {
        let that = this;
        let { PointDataList } = this.state;


        this.layer = new Layer();
        var longitudeString: any = null;
        var latitudeString: any = null;

        var cartesian = null;


        layers = this.layer.TileLayer({ Source: mapData[2] });
        this.maps = new Map({ id: 'map', layers: layers, coordinates: [119.8568965426516, 28.39425496950551], zoom: 14 });
        this.viewer = Viewer('map3D', [119.8568965426516, 28.39425496950551]);

        var scene = that.viewer.scene;

        //得到当前三维场景的椭球体
        var ellipsoid = scene.globe.ellipsoid;

        //监控相机高度
        var handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
        handler.setInputAction((res: any) => {

            cartesian = that.viewer.camera.pickEllipsoid(res.endPosition, ellipsoid);
            if (cartesian) {
                //将笛卡尔坐标转换为地理坐标
                var cartographic = ellipsoid.cartesianToCartographic(cartesian);
                //将弧度转为度的十进制度表示
                longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
                latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        // 监听鼠标移动
        const shijian = () => {
            let height = Math.ceil(this.viewer.camera.positionCartographic.height);

            //得到当前三维场景

            if (height > 1600) {
                // if (documents.getElementById("map3D").style.display === 'block') return;
                this.maps.getView().animate({
                    center: [longitudeString, latitudeString],
                    duration: 1,
                    zoom: 18
                });
                // this.viewer.imageryLayers.removeAll();
                this.setState({
                    Map2D3DIs_: true
                });

                this.maps.addLayer(layers[0])
                this.maps.addLayer(layers[1]);
                let pointLayer = Point.Icons({ Source: PointDataList });

                this.maps.addLayer(pointLayer)
                this.viewer.camera.setView({

                    destination: Cesium.Cartesian3.fromDegrees(longitudeString, latitudeString, 1000.0),
                    orientation: {
                        // 指向
                        heading: Cesium.Math.toRadians(90, 0),
                        // 视角
                        pitch: Cesium.Math.toRadians(-90),
                        roll: 0.0
                    }
                });
                this.eventHandler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);
            }
        }
        handler.setInputAction(shijian, Cesium.ScreenSpaceEventType.WHEEL);

        // 加载三维模型
        TilesetModel(this.viewer);

        this.maps.MouseScroll((e: any) => {
            // 添加三维地图
            if (this.maps.getView().getZoom() > 18) {
                this.maps.removeLayer(layers[0]);
                this.maps.removeLayer(layers[1]);
                this.setState({
                    Map2D3DIs_: false
                })
                if (this.viewer) {
                    // this.viewer.camera.DEFAULT_VIEW_RECTANGLE = new Cesium.Rectangle.fromDegrees(119.79711769553197, 31.48090108132136, 121.10322965960965, 30.611922615196686);//homebutton默认跳转位置


                    this.viewer.imageryLayers.addImageryProvider(TDTSWM);
                    this.viewer.imageryLayers.addImageryProvider(TDTSWM1);
                    this.viewer.imageryLayers.addImageryProvider(MapServer);

                    this.eventHandler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);

                    this.eventHandler.setInputAction(((el: any) => {
                        let pickPosition = this.viewer.scene.pickPosition(el.position);
                        if (!pickPosition) {
                            pickPosition = this.viewer.scene.camera.pickEllipsoid(el.startPosition, this.viewer.scene.globe.ellipsoid);
                        }
                        if (!pickPosition) return;
                        let code = "OBSERVATORY-" + new Date().getTime();
                        let c = Cesium.Cartographic.fromCartesian(pickPosition);
                        let position = Cesium.Cartesian3.fromDegrees(
                            Cesium.Math.toDegrees(c.longitude), Cesium.Math.toDegrees(c.latitude), c.height + 0.3
                        );
                        PointDataList.push({
                            longitude: Cesium.Math.toDegrees(c.longitude),
                            latitude: Cesium.Math.toDegrees(c.latitude),
                            text: '监控点位',
                            icon: JIANKONG,
                            scale: 0.2,
                            offsetY: -15
                        });
                        this.setState({
                            PointDataList
                        })
                        this.viewer.entities.add({
                            type: "Hotspot",
                            id: code,
                            plotCode: code,
                            position: position,
                            billboard: {
                                image: JIANKONG,
                                width: 64,
                                height: 64
                            },
                            label: {
                                text: '监控点位',
                                font: '14pt monospace',
                                style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                                outlineWidth: 2,
                                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                                pixelOffset: new Cesium.Cartesian2(0, -30)
                            }
                        });
                    }), Cesium.ScreenSpaceEventType.RIGHT_CLICK);

                    setTimeout(() => {
                        this.viewer.camera.setView({
                            // Cesium的坐标是以地心为原点，一向指向南美洲，一向指向亚洲，一向指向北极州
                            // fromDegrees()方法，将经纬度和高程转换为世界坐标

                            destination: Cesium.Cartesian3.fromDegrees(e.longitude, e.latitude, 1000.0),
                            orientation: {
                                // 指向
                                heading: Cesium.Math.toRadians(0, 0),
                                // 视角
                                pitch: Cesium.Math.toRadians(-90),
                                roll: 0.0
                            }
                        });
                    }, 10)
                    return;
                }
            };
        });


    }
    // 更新地图
    render() {
        let { Map2D3DIs_ } = this.state;
        return (
            <div >
                <div
                    id={'map'}
                    className={scss['map']}
                    style={{ display: Map2D3DIs_ ? 'block' : 'none' }}
                ></div>
                <div
                    id={'map3D'}
                    className={scss['map3D']}
                    style={{ display: !Map2D3DIs_ ? 'block' : 'none' }}
                ></div>
                <div className={scss['c-switch-ui']}>
                    <div>地图放大到18级时候会切换到三维地图</div>
                </div>
            </div>
        )
    }
}

const Viewer = (Tagid: any, lonlat: any) => {
    // Create view object
    let viewer = new Cesium.Viewer(Tagid, VIEHIDE) // Not shown by default
    // hide ceisum icon
    viewer.cesiumWidget.creditContainer.style.display = "none";
    // // Add a default sky map
    // viewer.imageryProvider = new Cesium.WebMapTileServiceImageryProvider(TDTSWM);

    viewer.camera.setView({
        // Cesium的坐标是以地心为原点，一向指向南美洲，一向指向亚洲，一向指向北极州
        // fromDegrees()方法，将经纬度和高程转换为世界坐标
        destination: Cesium.Cartesian3.fromDegrees(lonlat[0], lonlat[1], 750.0),
        orientation: {
            // 指向
            heading: Cesium.Math.toRadians(0, 0),
            // 视角
            pitch: Cesium.Math.toRadians(-90),
            roll: 0.0
        }
    });
    return viewer
}

const VIEHIDE = {
    baseLayerPicker: false,   // Layer selector
    animation: false,   // Instrument in the lower left corner
    fullscreenButton: false,   // Full screen button
    geocoder: false,   // Query search in the upper right corner
    infoBox: false,   // information
    homeButton: false,   //home button
    sceneModePicker: false,  //3d 2d select
    selectionIndicator: false,  //
    timeline: false,   // Timeline
    navigationHelpButton: false,  // Help button in the upper right corner
}

const MapServer = new Cesium.ArcGisMapServerImageryProvider({
    url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer'
}, 1)
const TDTSWM = new Cesium.WebMapTileServiceImageryProvider({
    //影像底图
    url: CLOUD_API.tdt3Dimg,
    subdomains: ["0", "1", "2", "3", "4", "5", "6", "7", "8"],
    layer: "tdtImgLayer",
    style: "default",
    format: "image/jpeg",
    tileMatrixSetID: "GoogleMapsCompatible",//使用谷歌的瓦片切片方式
    show: true
}, 1)
const TDTSWM1 = new Cesium.WebMapTileServiceImageryProvider({
    //影像注记
    url: CLOUD_API.tdt3Dcva,
    subdomains: ["0", "1", "2", "3", "4", "5", "6", "7", "8"],
    layer: "tdtCiaLayer",
    style: "default",
    format: "image/jpeg",
    tileMatrixSetID: "GoogleMapsCompatible",
    show: true
}, 2)

const TilesetModel = (viewer: any) => {
    var tilesetModel = new Cesium.Cesium3DTileset({
        url: CLOUD_API.addressModel,
        maximumScreenSpaceError: 2, // 模型加载清晰度调整
        maximumNumberOfLoadedTiles: 100,
    });
    viewer.scene.primitives.add(tilesetModel);
    //3dtile加载完成后执行

    tilesetModel.readyPromise.then(function (tilesetModel: any) {

        // 定位到3dtiles的位置
        viewer.camera.viewBoundingSphere(tilesetModel.boundingSphere, new Cesium.HeadingPitchRange(0, 0, 0));

        //高度偏差，向上是正数，向下是负数
        var heightOffset = -100.0;

        //计算tileset的绑定范围
        var boundingSphere = tilesetModel.boundingSphere;

        //计算中心点位置
        var cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center);

        //计算中心点位置的地表坐标
        var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);

        //偏移后的坐标
        var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, heightOffset);
        var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
        //tileset.modelMatrix转换
        tilesetModel.modelMatrix = Cesium.Matrix4.fromTranslation(translation);

    });
    //定位过去

    viewer.zoomTo(tilesetModel);

}
